package com.jmb.waimao.controller;

import com.jmb.waimao.service.MCPEmailToolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import java.util.HashMap;
import java.util.Map;

/**
 * Controller for AI chat interactions with MCP Email Service
 */
@RestController
@RequestMapping("/api/ai")
@Slf4j
public class AIChatController {

    @Autowired
    private MCPEmailToolService mcpEmailToolService;

    /**
     * Chat with AI and potentially trigger email actions
     *
     * @param message User message
     * @return AI response
     */
    @PostMapping("/chat")
    public ResponseEntity<Map<String, Object>> chat(@RequestBody Map<String, String> request) {
        String message = request.get("message");
        log.info("AI Chat: Received message: {}", message);

        // Simulate AI processing
        String response = processMessage(message);

        Map<String, Object> result = new HashMap<>();
        result.put("response", response);

        return ResponseEntity.ok(result);
    }

    /**
     * Process the user message and determine which tool to call
     *
     * @param message User message
     * @return AI response
     */
    private String processMessage(String message) {
        String lowerMessage = message.toLowerCase();

        if (lowerMessage.contains("status") || lowerMessage.contains("状态")) {
            Map<String, Object> status = mcpEmailToolService.getEmailServiceStatus();
            return "Email service status: " + status;
        } else if (lowerMessage.contains("send") || lowerMessage.contains("发送")) {
            // Extract email details from message
            String to = extractEmailAddress(message);
            if (to == null || to.isEmpty()) {
                to = "memberjee@163.com"; // Default recipient if none found
            }

            String subject = "来自AI助手的邮件";
            String content = message.replaceAll(".*发送.*邮件给.*?\\.com", "").trim();
            if (content.isEmpty()) {
                content = "这是一封通过AI助手使用MCP协议发送的测试邮件。";
            }

            Map<String, Object> result = mcpEmailToolService.sendEmail(to, subject, content);
            return "Email sending result: " + result;
        } else if (lowerMessage.contains("configure") || lowerMessage.contains("配置")) {
            // Extract configuration details from message
            String host = "smtp.qq.com"; // Default to QQ Mail
            Integer port = 587;

            // Extract host if present
            if (lowerMessage.contains("gmail")) {
                host = "smtp.gmail.com";
            } else if (lowerMessage.contains("qq")) {
                host = "smtp.qq.com";
            } else if (lowerMessage.contains("163")) {
                host = "smtp.163.com";
            }

            // Extract port if present
            if (lowerMessage.contains("port")) {
                try {
                    String portStr = lowerMessage.replaceAll(".*port\\s*(\\d+).*", "$1");
                    port = Integer.parseInt(portStr);
                } catch (Exception e) {
                    // Use default port if parsing fails
                }
            }

            Map<String, Object> result = mcpEmailToolService.configureEmailService(host, port, null, null, null);
            return "Email service configuration result: " + result;
        } else {
            return "I can help you send emails, check email service status, or configure the email service. Please let me know what you'd like to do.";
        }
    }

    /**
     * Extract email address from message
     *
     * @param message User message
     * @return Extracted email address or null if not found
     */
    private String extractEmailAddress(String message) {
        Pattern pattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
        Matcher matcher = pattern.matcher(message);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }
}
